let puppeteer = require('puppeteer');
var fs = require('fs')
var path = require('path')
var  screenshotDOMElement = async (page, selector, path, padding = 0) => {
  const rect = await page.evaluate(selector => {
      try{
          const element = document.querySelector(selector);

          const {x, y, width, height} = element.getBoundingClientRect();
          if(width * height != 0){
            return {left: x, top: y, width, height, id: element.id};
          }else{
            return null;
          }
      }catch(e){
        return null;
      }
  }, selector);
  return await page.screenshot({
      path: path,
      clip: rect ? {
      x: rect.left - padding,
      y: rect.top - padding,
      width: rect.width + padding * 2,
      height: rect.height + padding * 2
      } : null
  });
}
const a =  async (ctx) =>{
  // console.log(ctx)
  let req = ctx.request
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.setViewport({width: 337, height: 667, deviceScaleFactor: 2});
                // ！访问的地址
   var url = req.header.origin+ '/#/plan'+ req.url
   fs.exists(path.join(__dirname,'../public/images/1.png'), function(exists) {
    // console.log(exists)
    if(exists){
      fs.unlinkSync(path.join(__dirname,'../public/images/1.png'))
    }
  });
  console.log(url)
  await page.goto(url,{ waitUntil: ['networkidle2', 'load']})
  await page.waitForSelector('#finish');
  // await page.waitForSelector('#finish')
  // console.log(1)
  // page.on('requestfinished', async ( request ) => {
  //   // console.log( "request " + request.url())
  //   // console.log(request.resourceType())
  //   if (request.resourceType() === "xhr") {
  //     if(request.url().indexOf('http://172.16.181.143:7000/examSchedule.post')> -1) {
  //       console.log( "request " + request.url())
  //       await screenshotDOMElement(page,"body", './public/images/1.png');
  //     }
  //   }
  // })

  await screenshotDOMElement(page,"body", './public/images/1.png');
  //  await browser.close();

}


module.exports = a
